package com.alon.spring01.controller;

import com.alon.spring01.common.config.task.TaskService;
import com.alon.spring01.common.model.Result;
import com.alon.spring01.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Future;

/**
 * @program: spring01
 * @description: 任务测试控制器
 * @author: yulongguang
 * @create: 2019-08-02 09:25
 **/
@RestController
@Slf4j
@RequestMapping("/taskTest")
public class TaskTestController {

    @Autowired
    private TaskService taskService;

    @GetMapping("/task")
    public Result<?> task() {
        try {
            taskService.doTaskOne();
            taskService.doTaskTwo();
            taskService.doTaskThree();
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.error("任务执行出现异常：{}", e.getMessage());
        }

        return ResultUtil.ok();
    }

    /**
     * 异步并返回结果
     *
     * @return
     */
    @GetMapping("/futureTask")
    public Result<?> futureTask() {
        try {
            Future<String> stringFuture = taskService.doFutureTaskOne();
            Future<String> stringFuture1 = taskService.doFutureTaskTwo();
            Future<String> stringFuture2 = taskService.doFutureTaskThree();
            if (stringFuture.isDone() && stringFuture1.isDone() && stringFuture2.isDone()) {
                log.info("任务执行结束");
            }
            log.info("任务1的返回结果：{}，任务2的返回结果：{}，任务3的返回结果：{}", stringFuture.get(), stringFuture1.get(), stringFuture2.get());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("任务执行出现异常：{}", e.getMessage());
        }
        return ResultUtil.ok();
    }
}
